// pages/supply/supply2/supply2.js
import WxValidate from '../../../utils/WxValidate'
const app = getApp()
const api = require('../../../utils/util')
Page({
    // 页面分享
    onShareAppMessage () {},
    // 分享朋友圈
    onShareTimeline () {},

    /**
     * 页面的初始数据
     */
    data: {
      form:{
        url:'',
        url1:'',
        price: '',
        area: '',
        address: '',
        category: '',
        introduction:'',
        id: '',
        title: ''
      },
      show1:false,
      value02:'',
      category:[],
      disabled: ''
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
      if(options.id){
        let param = {
          id: options.id
        }
        let that = this
        let {form} = this.data
        api.supply2_one(param).then(function(res){
            form.id = res.data.id;
            form.title = res.data.title;
            form.url = app.globalData.siteUrl +  res.data.url;
            form.url1 = res.data.url;
            form.price = res.data.price;
            form.address = res.data.address;
            form.area = res.data.area;
            form.category = res.data.category;
            form.introduction = res.data.introduction;
            that.setData({
              form,
              value02: res.data.category
            })
        })
      }
      this.initValidate()
    },

     // 初始化表单验证
  initValidate() {
    //验证规则
    const rules = {
      url:{
        required: true
      },
      price: {
        required: true
      },
      title: {
        required: true,
      },
     
      category:{
        required: true
      }
    };
    //验证规则提示语，若不传则调用默认的信息
    const messages = {
      url:{
        required: "请上传图片"
      },
      price: {
        required: "请输入服务均价"
      },
      title: {
        required: "请输入服务标题",
      },
      
      category:{
        required: '请选择行业'
      }
    };

    this.WxValidate = new WxValidate(rules, messages)
  },


    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
      let that = this
      this.category(that)
    },

    showPop1(e){
      let name = e.currentTarget.dataset.name;
      this.setData({
        [name]:true
      })
    },
    onConfirm1(event) {
      const { picker, value, index } = event.detail;
      let {form} = this.data
      form.category = value
      this.setData({
        value02:value,
        form,
        show1:false
      })
    },
    onClose1(){
      this.setData({
        show1:false
      })
    },
     //获取分类
     category(that){
      
      api.get_category().then(function(res){
        let cate = [];
      
        for(let i = 0; i< res.data.length; i++){
           for(let j = 0; j< res.data[i].list.length; j++){
            cate.push(res.data[i].list[j].title)
           }
        }
         console.log(cate)
         that.setData({
          category: cate
         })
      })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },

    editHandle(e) {
      let {
        form
      } = this.data;
      form.introduction = e.detail.detail.html;
      this.setData({
        form
      });
  },
  editReadyHandle(e) {
      this.setData({
          editor: e.detail
      });
  
      this.data.editor.setContents({
          html: this.data.form.introduction
      })
  },

    // 通用输入函数
  inputHandle(e) {
    let { name } = e.currentTarget.dataset;
    let value = e.detail;
    let form = this.data.form;
    form[name] = value.trim();
    console.log(value.trim())
    this.setData({
      form
    });
  },

  // 提交
  submitHandle() {
    let {
      form
    } = this.data;
    
    // 表单验证
    if (!this.WxValidate.checkForm(this.data.form)) {
      const error = this.WxValidate.errorList[0];
      wx.showToast({
        title: error.msg,
        icon: 'none',
        image: '',
        duration: 1500,
        mask: false,
        success: (result)=>{
          
        },
        fail: ()=>{},
        complete: ()=>{}
      });
      return false
    }


    this.setData({
      disabled: 'disabled'
    })

    if(form.id){
      let param = {
        id: form.id,
        title: form.title,
        url:form.url1,
        price: form.price,
        area: form.area,
        address: form.address,
        introduction: form.introduction,
        category: this.data.value02
      }
      // 表单验证
      api.edit_supply2(param).then(function(res){
        if(res.code == '0'){
          wx.showToast({
            title: '修改成功',
            success:function(){ 
              setTimeout(function () {
                wx.redirectTo({
                  url: '/pages/message/record2/record2?tabsCurrent=1'
               })
               }, 2000)} 
          })
        }else{
          wx.showToast({
            title: '修改失败',
            icon: 'error'
          })
        }
         
      })
    }else{

      let param = {
        ucode: app.globalData.userinfo.ucode,
        url: form.url1,
        title: form.title,
        price: form.price,
        area: form.area,
        address: form.address,
        introduction: form.introduction,
        category: this.data.value02
      }
      // 表单验证
      console.log(param)
      api.add_supply2(param).then(function(res){
        if(res.code == '0'){
          wx.showToast({
            title: '添加成功',
            success:function(){ 
              setTimeout(function () {
                wx.navigateBack()
               }, 2000)} 
          })
        }else{
          wx.showToast({
            title: '添加失败请稍后再试',
            icon:'error'
          })
        }
        
      })
    }
  },

  afterRead(event) {
    const that = this;
    const { file } = event.detail;
    let {
      form
    } = this.data;
    var header = { 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8' };
    wx.uploadFile({
      url: app.globalData.uploadUrl, 
      filePath: file.url,
      name: 'file',
      header:header,
      formData: { user: 'test' },
      success(res) {
        var api_data = JSON.parse(res.data) 
        console.log(api_data.data.pic);
        // 上传完成需要更新 fileList
        form.url1 = api_data.data.pic;
      },
    });
    
    form.url = file.url;
    this.setData({
      form
    });
  }

})
